<template>
  <el-dialog v-model="dialogVisible" title="订单导出" width="800" :before-close="handleClose">
    <el-checkbox-group v-model="checkList">
      <el-checkbox :value="item.key" v-for="(item, index) in list" :key="index" :label="item.name" />
    </el-checkbox-group>
    <div style="margin-top: 20px;">
      <el-input v-model="excelName" placeholder="文件导出名称" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="save" :loading="loading">
          确 认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
const instance = getCurrentInstance();
const { proxy } = getCurrentInstance();

let dialogVisible = ref(false);
let model = {};
let selectList = []; //选中的数据
let excelName = ref("");
let checkList = ref([]);
let types = [];
let list = ref([
  { name: "报名时间", value: "_add_time" },
  { name: "培训分类", value: "curriculum_Info.type" },
  { name: "课程名称", value: "curriculum_Info.name" },
  { name: "姓名", value: "approvalContent.model.name" },
  { name: "联系方式", value: "approvalContent.model.mobile" },
  { name: "身份证号", value: "approvalContent.model.identityCard" },
  { name: "企业名称", value: "approvalContent.model.enterprise" },
  { name: "毕业专业", value: "approvalContent.model.graduationMajor" },
  { name: "累计工作年限", value: "approvalContent.model.workYears" },
  { name: "订单号", value: "out_trade_no" },
  { name: "报名所属", value: "approvalContent.model.affiliation" },
  { name: "课程内容", value: "approvalContent.selectLesson" },
  { name: "课程价格", value: "price" },
  { name: "报名状态", value: "status" },
]);
let loading = ref(false);

let open = (params, arr) => {
  getTypes();
  model = { ...params };
  selectList = proxy.$utils.deepcopy(arr);
  excelName.value = "";
  dialogVisible.value = true;
};

let handleClose = () => {
  model = {};
  selectList = [];
  checkList.value = [];
  dialogVisible.value = false;
};

async function save() {
  try {
    // 获取 a 中的 name 值
    const aNames = [...list.value].map((item) => item.name);
    // 根据 a 中的顺序对 b 进行排序
    const sortedB = [...checkList.value].sort((x, y) => {
      return aNames.indexOf(x) - aNames.indexOf(y);
    });

    if (selectList.length) {
      let arr = [];
      selectList.forEach((element) => {
        let fieldObj = {};
        sortedB.forEach((item) => {
          fieldObj[item] = format_fn(element, item);
        });
        arr.push(fieldObj);
      });
      await downExcel(arr);
    } else {
      loading.value = true;
      let { total } = await getInfo();
      let lista = [];
      let totalPage = proxy.$utils.pageCount(total, model.pageSize);
      for (let index = 1; index <= totalPage; index++) {
        model.pageIndex = index;
        let { rows } = await getInfo();
        lista.push(...rows);
      }
      let arr = [];

      lista.forEach((element) => {
        let fieldObj = {};
        sortedB.forEach((item) => {
          fieldObj[item] = format_fn(element, item);
        });
        arr.push(fieldObj);
      });
      await downExcel(arr);
    }
  } catch (error) {
    console.log("导出哪里有问题", error);
  } finally {
    loading.value = false;
  }
}

async function getInfo() {
  return await proxy.$apis.orderAction({
    type: "list",
    data: model,
  });
}

function format_fn(element, item) {
  let index = proxy.$utils.findIndexByField(list.value, "name", item);
  let key = list.value[index].value;
  //console.log(element, item, key);
  let arr = ["_add_time", "out_trade_no", "price", "status"];
  if (arr.includes(key)) {
    if (key == "_add_time") {
      return proxy.$utils.dateTimeFormateFn(element[key], "all");
    } else if (key == "status") {
      if (element.status == 1 && element.rejectMsg) {
        return "已驳回";
      } else {
        return status_format(element.status);
      }
    } else {
      return element[key];
    }
  } else if (key == "curriculum_Info.type") {
    return type_format(getValueByPath(element, key));
  } else if (key == "approvalContent.model.affiliation") {
    //报名所属
    let a = getValueByPath(element, key);
    return affiliation_format(a);
  } else if (key == "approvalContent.selectLesson") {
    let array = getValueByPath(element, key);
    let arr = [];
    array.forEach((element) => {
      arr.push(element.name);
    });
    return arr.toString();
  } else {
    return getValueByPath(element, key);
  }
}

function affiliation_format(e) {
  if (!e) return "-";
  if (proxy.$utils.isString(e)) {
    return e;
  } else if (proxy.$utils.isArrayOrJsonArray(e)) {
    return e.toString();
  } else {
    return "-";
  }
}

function status_format(e) {
  let tabs = [
    { name: "全部", value: "" },
    { name: "待审核", value: 1 },
    { name: "报名成功", value: 2 },
    { name: "已退款", value: 4 },
    { name: "取消订单", value: 6 },
    { name: "已开票", value: 7 },
  ];
  for (let index = 0; index < tabs.length; index++) {
    const element = tabs[index];
    if (element.value == e) return element.name;
  }
}

async function getTypes() {
  types = await proxy.$apis.webCurriculum({
    type: "query",
  });
}

function type_format(e) {
  if (!types.length) return;
  if (!e) return;
  let index = proxy.$utils.findIndexByField(types, "_id", e[0]);
  return types[index].name;
}

function getValueByPath(obj, path) {
  const keys = path.split(".");
  let result = obj;
  for (let i = 0; i < keys.length; i++) {
    if (result === undefined) {
      return undefined; // 如果中途路径不存在，返回undefined
    }
    result = result[keys[i]];
  }
  return result; // 如果路径存在，返回最终的值
}

async function downExcel(arr) {
  let cols = []; //设置表头样式
  checkList.value.forEach((element) => {
    cols.push({ wch: 20 });
  });
  let query = {
    jsonData: arr,
    cols,
  };
  await proxy.$utils.exportToExcel(
    query,
    excelName.value ? excelName.value : "订单列表导出"
  );
  handleClose();
}

defineExpose({ open });
</script>



<style lang="scss" scoped>
.container {
}
</style>